Map转json格式string字符串

##工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.List;
import java.util.Map;

/**
* @Description map 转 json格式string字符串
* @Date 2022-05-08
*/
public class MapToJson {
public static String mapTojsonString(Map<String, Object> map) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("{");
if (map != null && map.size() > 0) {
for (String key : map.keySet()) {
if (!stringBuilder.toString().endsWith("{")) {stringBuilder.append(",");}

String value = mapTojsonString(map.get(key));
stringBuilder.append("\"").append(key).append("\"")
.append(":")
.append(value);
}
}
stringBuilder.append("}");
return stringBuilder.toString();
}

static String mapTojsonString(Object obj) {
if (obj instanceof String) {return "\"" + obj.toString() + "\"";}
if (obj instanceof Map) {return mapTojsonString((Map) obj);}
if (obj instanceof List) {return listToString((List<Object>) obj);}
if (obj == null) {return null;}
return obj.toString();
}

static String listToString(List<Object> list) {
StringBuilder builder = new StringBuilder();
builder.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
if (!builder.toString().endsWith("[")){ builder.append(",");}
builder.append(mapTojsonString(obj));
}
}
builder.append("]");
return builder.toString();
}
}

##使用

1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String[] args) {


List<Map<String, String>> list = new ArrayList<>();

Map<String, Object> map1 = new HashMap<>();
map1.put("name", "张三");
map1.put("age", "18");
map1.put("gender", "男");

System.out.println(mapTojsonString(map1));
}

一辈子很短,努力的做好两件事就好;
第一件事是热爱生活,好好的去爱身边的人;
第二件事是努力学习,在工作中取得不一样的成绩,实现自己的价值,而不是仅仅为了赚钱;

继开 wechat
欢迎加我的微信,共同交流技术